#include	"SoundSystem.h"
#include	"SoundException.h"

SoundSystem::SoundSystem(Config & config)
	:	m_config(&config)
	,	m_system(0)
{
	FMOD_RESULT result = FMOD::System_Create(&m_system);
	if(result != FMOD_OK)
	{
		throw SoundException(result);
	}
	result = m_system->setOutput(FMOD_OUTPUTTYPE_DSOUND);
	if (result != FMOD_OK)
	{
		throw SoundException(result);
	}
	result = m_system->init(m_config->sound.channels, FMOD_INIT_DSOUND_HRTFLIGHT, 0);
	if (result != FMOD_OK)
	{
		throw SoundException(result);
	}

}

SoundSystem::~SoundSystem()
{
	Cleanup();
}

void SoundSystem::Cleanup()
{
	m_config = 0;
	m_system->release();
	m_system = 0;
}

void SoundSystem::Update()
{
	FMOD_RESULT result = m_system->update();
	if(result != FMOD_OK)
	{
		throw SoundException(result);
	}
}

FMOD::Sound * SoundSystem::CreateSound(const std::string & filename, bool loop)
{
	FMOD_MODE mode = FMOD_2D | FMOD_CREATESAMPLE | FMOD_HARDWARE;// | FMOD_NONBLOCKING;
	if(loop)
	{
		mode |= FMOD_LOOP_NORMAL;
	}
	else
	{
		mode |= FMOD_LOOP_OFF;
	}
	FMOD::Sound * sound = 0;
	FMOD_RESULT result = m_system->createSound(filename.c_str(), mode, 0, &sound);
	if(result != FMOD_OK)
	{
		throw SoundException(result);
	}
	return sound;
}

FMOD::Channel * SoundSystem::PlaySound(FMOD::Sound * sound, float volume, bool paused)
{
	FMOD::Channel * channel = 0;
	FMOD_RESULT result = m_system->playSound(FMOD_CHANNEL_FREE, sound, true, &channel);
	if(result != FMOD_OK)
	{
		throw SoundException(result);
	}
	result = channel->setVolume(volume / 100.0f);
	if(result != FMOD_OK)
	{
		throw SoundException(result);
	}
	result = channel->setPaused(paused);
	if(result != FMOD_OK)
	{
		throw SoundException(result);
	}
	return channel;
}

